"use strict";

var STATES = Object.freeze({
    INVALID: "invalid",
    UNKNOWN: "unknown",
    NO_ANALYTICS: "no_analytics",
    NOT_BLOCKED: "not_blocked",
    BLOCKED: "blocked"
}), websiteList = [], showPopupMenuClose = !1, isExtensionUpdated = !1;

function optionsLoad(data) {
    isExtensionUpdated = $.options.getBoolean(data.isExtensionUpdated, !1);
    websiteList = $.options.getObject(data.websiteList, []);
    showPopupMenuClose = $.options.getBoolean(data.showPopupMenuClose, !1);
    optionsAfterChange();
}

function optionsChanged(changes, namespace) {
    if (namespace === myStorage.__storageType) {
        for (var key in changes) switch (key) {
          case "websiteList":
            websiteList = $.options.getObject(changes[key].newValue, []);
            0;
            break;

          case "showPopupMenuClose":
            showPopupMenuClose = $.options.getBoolean(changes[key].newValue, !1);
        }
    }
}

function optionsAfterChange() {
    chrome.tabs.query({
        windowType: "normal"
    }, function(tabs) {
        for (var tab, i = 0; i < tabs.length; i++) -1 !== (tab = tabs[i]).id && void 0 !== tab.url && 0 === tab.url.indexOf("http") && 0 !== tab.url.indexOf($.storeUrl) && setActionState(tab.id, STATES.UNKNOWN);
    });
}

function ruleIsEnabled(domainName) {
    for (var i = 0; i < websiteList.length; i++) if ("m" === websiteList[i].type) {
        if (domainName === websiteList[i].website) return !0;
    } else if ("w" === websiteList[i].type) {
        if (domainName.match(websiteList[i].regex)) return !0;
    } else if (domainName.match(websiteList[i].website)) return !0;
    return !1;
}

function setActionState(tabId, state) {
    var iconPath, title;
    if (state === STATES.INVALID) {
        title = "Extension not available for this website";
        iconPath = {
            16: "images/icon-disabled-016.png",
            19: "images/icon-disabled-019.png",
            32: "images/icon-disabled-032.png",
            38: "images/icon-disabled-038.png"
        };
    } else if (state === STATES.NO_ANALYTICS) {
        title = "Analytics not detected on this page";
        iconPath = {
            16: "images/icon-disabled-016.png",
            19: "images/icon-disabled-019.png",
            32: "images/icon-disabled-032.png",
            38: "images/icon-disabled-038.png"
        };
    } else if (state === STATES.BLOCKED) {
        title = "Analytics blocked";
        iconPath = {
            16: "images/icon-blocked-016.png",
            19: "images/icon-blocked-019.png",
            32: "images/icon-blocked-032.png",
            38: "images/icon-blocked-038.png"
        };
    } else if (state === STATES.NOT_BLOCKED) {
        title = "Analytics not blocked";
        iconPath = {
            16: "images/icon-016.png",
            19: "images/icon-019.png",
            32: "images/icon-032.png",
            38: "images/icon-038.png"
        };
    } else {
        if (state !== STATES.UNKNOWN) return;
        title = "Please reload page to initialise extension";
        iconPath = {
            16: "images/icon-disabled-016.png",
            19: "images/icon-disabled-019.png",
            32: "images/icon-disabled-032.png",
            38: "images/icon-disabled-038.png"
        };
    }
    chrome.browserAction.setIcon({
        tabId: tabId,
        path: iconPath
    });
    chrome.browserAction.setTitle({
        tabId: tabId,
        title: title
    });
}

function toggleActiveWebsite(url) {
    for (var found = !1, urlStriped = $.domainFromURL(url), i = 0; i < websiteList.length; i++) {
        "m" === websiteList[i].type ? urlStriped === websiteList[i].website && (found = !0) : "w" === websiteList[i].type ? urlStriped.match(websiteList[i].regex) && (found = !0) : urlStriped.match(websiteList[i].website) && (found = !0);
        if (found) {
            websiteList.splice(i, 1);
            break;
        }
    }
    found || websiteList.push({
        website: urlStriped,
        type: "m"
    });
    $.storage.set(myStorage.__storageType, {
        websiteList: websiteList
    }, null, function(error) {
        window.console.error(error);
    });
}

function onBeforeRequestTracking(info) {
    var url = info.initiator || info.originUrl, isBlock = ruleIsEnabled($.domainFromURL(url));
    setActionState(info.tabId, isBlock ? STATES.BLOCKED : STATES.NOT_BLOCKED);
    return {
        cancel: isBlock
    };
}

function extensionUpdatedShowChangeLog() {
    extensionUpdatedNotified();
    $.tab.open("https://dev.tekin.cn/?ref=block-yourself-from-analytics/change-log-" + $.browserSlug + "-updated#content");
}

function extensionUpdatedNotified() {
    isExtensionUpdated = !1;
    chrome.storage.local.remove("isExtensionUpdated");
    $.icon.badge.text = "";
}

myStorage.init(function(data) {
    if (!data.version || $.verCompare(data.version, "3.0.0") < 0) {
        if (data.version) {
            data.isExtensionUpdated = !0;
            $.storage.set(STORAGE_TYPE.LOCAL, {
                isExtensionUpdated: !0
            }, null, function(error) {
                window.console.error(error);
            });
            $.icon.badge.text = "new";
        }
        $.storage.set(myStorage.__storageType, {
            version: "3.0.0"
        }, null, function(error) {
            window.console.error(error);
        });
    }
    optionsLoad(data);
    $.storage.onChangedListen(optionsChanged);
    chrome.webRequest.onBeforeRequest.addListener(onBeforeRequestTracking, {
        urls: [ "*://hm.baidu.com/hm*", "*://cbjs.baidu.com/*", "*://*.users.51.la/*", "*://img.chinaz.com/*", "*://s3a.pstatp.com/*", "*://*.cnzz.com/stat*", "*://a2put.chinaz.com/*", "*://*.statcounter.com/*", "*://www.googletagmanager.com/gtag/js*", "*://www.googletagmanager.com/*", "*://*.google-analytics.com/analytics.js", "*://*.google-analytics.com/collect*", "*://*.google-analytics.com/*/collect*", "*://stats.g.doubleclick.net/dc.js", "*://stats.g.doubleclick.net/collect*", "*://stats.g.doubleclick.net/*/collect*", "*://*.google-analytics.com/ga.js", "*://*.google-analytics.com/__utm.gif*", "https://cdn.jsdelivr.net/npm/ga-lite@2/dist/ga-lite.min.js", "*://*.cloudfront.net/*" ],
        types: [ "script", "image", "ping", "xmlhttprequest" ]
    }, [ "blocking" ]);
}, function() {
    $.icon.badge.backgroundColor = [ 255, 0, 0, 255 ];
    $.icon.badge.text = "?";
    $.icon.title = "Error reading data - unable to initialize extension";
});